(function(window, document, undefined) {
    //initiate dataTables plugin
    var defaultConfig = {
        bAutoWidth: false,
        language: {
            "sProcessing":   "处理中...",
            "sLengthMenu":   "每页 _MENU_ 项",
            "sZeroRecords":  "没有匹配结果",
            "sInfo":         "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。(在_MAX_项结果过滤) ",
            "sInfoEmpty":    "当前显示第 0 至 0 项，共 0 项 ",
            "sInfoFiltered": "(在_MAX_项结果过滤)",
            "sInfoPostFix":  "",
            "sSearch":       "搜索:",
            "sUrl":          "",
            "sEmptyTable":     "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands":  ",",
            "oPaginate": {
                "sFirst":    "首页",
                "sPrevious": "上页",
                "sNext":     "下页",
                "sLast":     "末页",
                "sJump":     "跳转"
            },
            "oAria": {
                "sSortAscending":  ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        },
        //"bProcessing": true,
        //"bServerSide": true,
        //"sAjaxSource": "http://127.0.0.1/table.php"	,

        //,
        //"sScrollY": "200px",
        //"bPaginate": false,

        //"sScrollX": "100%",
        //"sScrollXInner": "120%",
        //"bScrollCollapse": true,
        //Note: if you are applying horizontal scrolling (sScrollX) on a ".table-bordered"
        //you may want to wrap the table inside a "div.dataTables_borderWrap" element

        //"iDisplayLength": 50

        select: {
            style: 'multi'
        },
        //searching: false,    //is show searching

        //自定义
        showTablesTools:true,//is show tablesTools eg export
        tableToolsContainer :'.tableTools-container', //tablesTools container values is jquerySelect
        addOperaterBtns:null,//{columnIndex:0,buttons:[...]}arrays for add button operator column
    };
    
    window.initDataTables = function(tableID,options){
        options = $.extend({}, defaultConfig, options);

        if(options.addOperaterBtns&&!options.createdRow){
            options.createdRow = function(row, data, index){
                var $opDivWrap = $('<div class="hidden-sm hidden-xs action-buttons"></div>');
                var $opDivWrapHidden = $('<div class="hidden-md hidden-lg"> <div class="inline pos-rel"> ' +
                                         '    <button class="btn btn-minier btn-yellow dropdown-toggle" data-toggle="dropdown" data-position="auto"><i class="ace-icon fa fa-caret-down icon-only bigger-120"></i>'+
                                         '    </button>  ' +
                                         '<ul class="dropdown-menu dropdown-only-icon dropdown-yellow dropdown-menu-right dropdown-caret dropdown-close"></ul>'+
                                         '</div></div>');
                for(var i in options.addOperaterBtns.buttons){
                    $opDivWrap.append(options.addOperaterBtns.buttons[i]);
                    $opDivWrapHidden.find("ul").append('<li>'+options.addOperaterBtns.buttons[i]+'</li>');
                }
                $("td",row).eq(options.addOperaterBtns.columnIndex).append($opDivWrap).append($opDivWrapHidden);
                $(row).find('[title]').tooltip({title: this.title, animation:false, container:'body','placement':'left',template: '<div class="tooltip tooltip-info "><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'});
            }
        }

        var $table = $("#"+tableID);
        var myTable = $table
            //.wrap("<div class='dataTables_borderWrap' />")   //if you are applying horizontal scrolling (sScrollX)
            .DataTable(options);
        
        if(options.showTablesTools){
            $.fn.dataTable.Buttons.swfPath = "../assets/js/dataTables/extensions/buttons/swf/flashExport.swf"; //in Ace demo ../assets will be replaced by correct assets path
            $.fn.dataTable.Buttons.defaults.dom.container.className = 'dt-buttons btn-overlap btn-group btn-overlap';

            new $.fn.dataTable.Buttons(myTable, {
                buttons: [
                    {
                        "extend": "colvis",
                        "text": "<i class='fa fa-eye bigger-110 blue'></i> <span class='hidden'>显示/隐藏列</span>",
                        "className": "btn btn-sm btn-white btn-primary btn-bold",
                        columns: ':not(:first):not(:last)'
                    },
                    {
                        "extend": "copy",
                        "text": "<i class='fa fa-copy bigger-110 pink'></i> <span class='hidden'>复制到剪贴板</span>",
                        "className": "btn btn-sm btn-white btn-primary btn-bold"
                    },
                    {
                        "extend": "csv",
                        "text": "<i class='fa fa-database bigger-110 orange'></i> <span class='hidden'>导出CSV</span>",
                        "className": "btn btn-sm btn-white btn-primary btn-bold"
                    },
                    {
                        "extend": "excel",
                        "text": "<i class='fa fa-file-excel-o bigger-110 green'></i> <span class='hidden'>导出Excel</span>",
                        "className": "btn btn-sm btn-white btn-primary btn-bold"
                    },
                    {
                        "extend": "pdf",
                        "text": "<i class='fa fa-file-pdf-o bigger-110 red'></i> <span class='hidden'>导出PDF</span>",
                        "className": "btn btn-sm btn-white btn-primary btn-bold"
                    },
                    {
                        "extend": "print",
                        "text": "<i class='fa fa-print bigger-110 grey'></i> <span class='hidden'>打印</span>",
                        "className": "btn btn-sm btn-white btn-primary btn-bold",
                        autoPrint: false,
                        message: '此打印是使用DataTable的打印按钮生成'
                    }
                ]
            });
            myTable.buttons().container().appendTo($(options.tableToolsContainer));

            //style the message box
            var defaultCopyAction = myTable.button(1).action();
            myTable.button(1).action(function (e, dt, button, config) {
                defaultCopyAction(e, dt, button, config);
                $('.dt-button-info').addClass('gritter-item-wrapper gritter-info gritter-center white');
            });

            var defaultColvisAction = myTable.button(0).action();
            myTable.button(0).action(function (e, dt, button, config) {
                defaultColvisAction(e, dt, button, config);
                if ($('.dt-button-collection > .dropdown-menu').length == 0) {
                    $('.dt-button-collection')
                        .wrapInner('<ul class="dropdown-menu dropdown-light dropdown-caret dropdown-caret" />')
                        .find('a').attr('href', '#').wrap("<li />")
                }
                $('.dt-button-collection').appendTo(options.tableToolsContainer+' .dt-buttons')
            });

            setTimeout(function () {
                $($(options.tableToolsContainer)).find('a.dt-button').each(function () {
                    var div = $(this).find(' > div').first();
                    if (div.length == 1) div.tooltip({container: 'body', title: div.parent().text()});
                    else $(this).tooltip({container: 'body', title: $(this).text()});
                });
            }, 500);
        }

        myTable.on('select', function (e, dt, type, index) {
            if (type === 'row') {
                $(myTable.row(index).node()).find('input:checkbox').prop('checked', true);
            }
        });
        myTable.on('deselect', function (e, dt, type, index) {
            if (type === 'row') {
                $(myTable.row(index).node()).find('input:checkbox').prop('checked', false);
            }
        });
        
        //select/deselect all rows according to table header checkbox
        $table.find('> thead > tr > th input[type=checkbox], #dynamic-table_wrapper input[type=checkbox]').eq(0).on('click', function () {
            var th_checked = this.checked;//checkbox inside "TH" table header

            $('#dynamic-table').find('tbody > tr').each(function () {
                var row = this;
                if (th_checked) myTable.row(row).select();
                else  myTable.row(row).deselect();
            });
        });

        //select/deselect a row when the checkbox is checked/unchecked
        $table.on('click', 'td input[type=checkbox]', function () {
            var row = $(this).closest('tr').get(0);
            if (!this.checked) myTable.row(row).deselect();
            else myTable.row(row).select();
        });
        
        myTable[0] = $table;
        return myTable;
    };

    //所有复选框取消选中
    //$('th input[type=checkbox], td input[type=checkbox]').prop('checked', false);
    
})(window, document);